import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_soft.dart';
import 'package:osc/models/entity/osc_soft_recommend_list_entity.dart';
import 'package:osc/models/entity/widget_item/project_catalog_item.dart';
import 'package:osc/models/local_data/project_catalog_item_data.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/colors.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/pages/project/project_banner.dart';
import 'package:osc/ui/pages/project/project_detail_page.dart';
import 'package:osc/ui/pages/project/project_list_fragment.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'open_source_company_page.dart';

///软件
class ProjectRecommendListFragment extends StatefulWidget {
  const ProjectRecommendListFragment({Key key,}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new ProjectRecommendListFragmentState();
  }
}

class ProjectRecommendListFragmentState extends State<ProjectRecommendListFragment> with AutomaticKeepAliveClientMixin<ProjectRecommendListFragment> {

  HttpRepository httpRepository;
  int page = 0;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscSoftListItem> list;

  RefreshController controller = RefreshController(initialRefresh: false);
  ScrollPhysics scrollPhysics = ScrollPhysics();


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
    refresh();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: buildListViewWithBanner(),
    );
  }

  buildListViewWithBanner(){
    return ListView(
      physics: scrollPhysics,
      children: <Widget>[
//        OscProjectBannerWidget(),
        ProjectBanner(),
        buildCatalog(),
        buildListViewTitle(),
        buildListView(),
      ],
    );
  }


  buildCatalog(){
    List<ProjectCatalogItem> items = ProjectCatalogItemData().getCatalogItems();
    return Container(
      color: Colors.white,
      child: GridView.builder(
        shrinkWrap: true,
        primary: false,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
        itemBuilder: (BuildContext context, int index){
          return buildCatalogItem(items.elementAt(index));
        },
        itemCount: items.length,
      ),
    );
  }

  buildCatalogItem(ProjectCatalogItem item){
    return GestureDetector(
      onTap: (){
        switch(item.catalog){
          case ProjectCatalogItem.CATALOG_TYPE:
            break;
          case ProjectCatalogItem.CATALOG_HOT_CN:
          case ProjectCatalogItem.CATALOG_LATEST:
            jump2PageForResult(CommonPage(title: item.title, body: ProjectListFragment(catalog: item.catalog,)));
            break;
          case ProjectCatalogItem.CATALOG_COMPANY:
            jump2PageForResult(OpenSourceCompanyPage());
            break;
        }
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(PdUtil.getImagePath(item.imageName), width: Dimens.view_item_icon_height_bigger, fit: BoxFit.fitWidth,),
          Padding(
              padding: EdgeInsets.only(top: Dimens.gap_view_normal),
            child: buildText(item.title, Colors.black54, Dimens.font_sp10),
          ),
        ],
      ),
    );
  }

  buildListViewTitle(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, ),
      color: Colors.white,
      child: SmallWidgets.buildText("编辑推荐", Colors.black, Dimens.font_sp16, fontWeight: FontWeight.bold),
    );
  }

  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
      shrinkWrap: true,
      physics: scrollPhysics,
    );
  }

  buildListItem(int index){
    OscSoftListItem item = list.elementAt(index);
    return item.type.compareTo("project") == 0? buildSoftInfo(item.project) : buildAuthorList(item.authors);
  }

  buildSoftInfo(OscSoft project){
    return GestureDetector(
      onTap: (){
        jumpToPageForResult(ProjectDetailPage(id: project.id,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
        child: Row(
          children: <Widget>[
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    buildTitle(project),
                    buildDescription(project.desc),
                    buildBottom(project),
                  ],
                )
            ),
            Offstage(
              offstage: StringUtil.isEmpty(project.logo),
              child: Padding(
                padding: EdgeInsets.only(left: Dimens.gap_view_big),
                child: SizedBox(
                  width: Dimens.view_item_icon_height_biggest,
                  child: ImageLoader(url: project.logo,),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildTitle(OscSoft project){
    List<TextSpan> textSpans = List<TextSpan>();
    if(project.cn != null && project.cn){
      textSpans.add(buildImageSpan("ic_label_cn", EdgeInsets.only(right: Dimens.gap_view_small)));
    }
    if(project.recommend){
      textSpans.add(buildImageSpan("ic_label_recommend", EdgeInsets.only(right: Dimens.gap_view_smaller)));
    }
    textSpans.add(buildTextSpan(text:" "+project.name, color: Colors.black, fontSize: Dimens.font_sp14, fontWeight: FontWeight.bold));
    if(!StringUtil.isEmpty(project.title)){
      textSpans.add(buildTextSpan(text:" "+project.title));
    }
    return RealRichText(
        textSpanList:textSpans,
    );
  }

  buildTextSpan({String text, Color color = Colors.black54, double fontSize = Dimens.font_sp14, FontWeight fontWeight = FontWeight.normal}){
    return TextSpan(
      text: text,
      style: TextStyle(color: color, fontSize: fontSize, fontWeight: fontWeight),
    );
  }

  buildImageSpan(String imageName, EdgeInsets margin){
    return ImageSpan(
      AssetImage(PdUtil.getImagePath(imageName)),
      imageWidth: Dimens.view_item_tag_height_small,
      imageHeight: Dimens.view_item_tag_height_small,
      margin: margin,
    );
  }
  
  buildTitleIcon(bool show, String imageName){
    return Offstage(
      offstage: !show,
      child: Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_tag_height_smaller, fit: BoxFit.fitWidth,),
    );
  }
  
  buildDescription(String msg){
    return Padding(
        padding: EdgeInsets.only(top: Dimens.gap_view_normal),
      child: Text(
        msg,
        style: TextStyle(
            color: Colors.black54,
            fontSize: Dimens.font_sp10
        ),
        maxLines: 2,
        softWrap: true,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }


  buildBottom(OscSoft project){
    return Padding(
      padding: EdgeInsets.only(top: paddingChildVertical),
      child: Row(
        children: <Widget>[
          buildBottomItem("ic_fav_normal", "${project.collectNumber}"),
          Padding(
              padding: EdgeInsets.only(left: Dimens.gap_view_bigger),
            child: buildBottomItem("ic_comment_30", "${project.replyCount}"),
          ),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, String text){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smallest, fit: BoxFit.fitWidth,),
        buildText(" $text", Colors.black54, Dimens.font_sp10)
      ],
    );
  }

  buildAuthorList(List<OscSoftAuthor> authors){
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
      height: Dimens.view_soft_author_height,
      width: ScreenUtil.getInstance().screenWidth,
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
          itemCount: authors.length,
          itemBuilder: (BuildContext context, int index){
            return buildAuthor(authors.elementAt(index), index);
          }
      ),
    );
  }
  
  buildAuthor(OscSoftAuthor author, int index){
    return Container(
      margin: EdgeInsets.only(right: Dimens.gap_view_big, left: index==0?Dimens.gap_view_big:0),
      padding: EdgeInsets.all(Dimens.gap_view_bigger),
      width: ScreenUtil.getInstance().screenWidth*3/4,
      decoration: BoxDecoration(
        color: Colours.bg_list_tab,
        border: Border.all(color: Colors.black12),
        borderRadius: BorderRadius.all(Radius.circular(Dimens.view_radius_size_small))
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            children: <Widget>[
              OscPortraitWidget(id: author.userID, portraitImageUrl: author.portrait),
              Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: Dimens.gap_view_normal),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        SmallWidgets.buildText(author.name, Colors.black87, Dimens.font_sp14, fontWeight: FontWeight.bold),
                        SmallWidgets.buildText("${author.project} 作者", Colors.black87, Dimens.font_sp12),
                      ],
                    ),
                  ),
              ),
            ],
          ),
          SmallWidgets.buildLineBigger(color: Colors.transparent),
          Row(
            children: <Widget>[
              buildText("${author.projectCount} 软件  ${author.followers} 粉丝", Colors.black45, Dimens.font_sp10),
              Expanded(
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                      alignment: Alignment.center,
                      width: Dimens.view_button_height_small*2,
                      height: Dimens.view_button_height_smaller,
                      decoration: BoxDecoration(
                        color: Colors.green,
                        borderRadius: BorderRadius.all(Radius.circular(Dimens.view_radius_size_smaller))
                      ),
                      child: InkWell(
                        onTap: (){
                          reverserRelation(author: author);
                        },
                        child: buildText(author.followStatus == 1? "+ 关注" : "已关注", Colors.white, Dimens.font_sp12),
                      ),
                    ),
                  )
              ),
            ],
          ),
        ],
      ),
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    page = 1;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    List<OscSoftListItem> tempList;
    int tempSize = 0;
    await httpRepository.getProjectRecommendList(page: page).then((resp){
      if(resp != null && resp.success){
        OscSoftRecommendListEntity entity = resp.result;
        if(entity != null){
          tempList = entity.data?.items;
        }
      }
    });
    tempSize = tempList?.length??0;
    if(page == 1){
      list = tempList;
    } else {
      list.addAll(tempList);
    }
    size = list?.length??0;
    if(tempSize == Constant.PAGE_SIZE){
      page++;
    }
    if(mounted) {
      setState(() {
        controller.loadComplete();
        controller.refreshCompleted();
      });
    }
  }

  Future<Null> reverserRelation({@required OscSoftAuthor author}) async{
    await httpRepository.reverseRelation(id: author.userID).then((resp) {
      if(resp.success){
        int relation = resp.result.relation;
        showTips(relation == 1 || relation == 2?"关注成功":"取消关注");
        if(mounted){
          setState(() {
            author.followStatus = relation == 1 || relation == 2? 2 : 1;
          });
        }
      }
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  @override
  bool get wantKeepAlive => true;
}
